<template>
  <div class="breeding-info">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>养殖信息管理</h2>
      <p class="page-description">管理养殖过程中的各项信息，包括基本信息、免疫记录、动检证和企业照片</p>
    </div>

    <!-- 养殖信息设置 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>养殖信息</h3>
          <el-button type="primary" size="small" @click="openBreedingSettings">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
        </div>
      </template>

      <!-- 养殖基本信息 -->
      <div class="breeding-basic-info" :data="CultivationData">
        <div class="info-grid">
          <div class="info-item">
            <label>品种</label>
            <span>{{ CultivationData.variety || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>来源</label>
            <span>{{ CultivationData.source || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>饲养天数</label>
            <span>{{ CultivationData.rearingDays || 0 }}天</span>
          </div>
          <div class="info-item">
            <label>饲料品牌</label>
            <span>{{ CultivationData.brand || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>饲养负责人</label>
            <span>{{ CultivationData.rearingLeader || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>出栏日期</label>
            <span>{{ CultivationData.outDate ? formatDate(CultivationData.outDate) : '未设置' }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 免疫信息 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>免疫信息</h3>
          <el-button type="primary" size="small" @click="addImmunizationRow">
            <el-icon><Plus /></el-icon>
            新增记录
          </el-button>
        </div>
      </template>

      <!-- 免疫信息表格 -->
      <el-table :data="immunizationList" border style="width: 100%" class="immunization-table">
        <el-table-column prop="rearingDays" label="饲养天数" align="center" width="120">
          <template #default="{ row }">
            <el-input v-if="row.isEditing" v-model="row.rearingDays" size="small" />
            <span v-else>{{ row.rearingDays }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="way" label="免疫方式" align="center" width="150">
          <template #default="{ row }">
            <el-input v-if="row.isEditing" v-model="row.way" size="small" />
            <span v-else>{{ row.way }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="function" label="免疫方法" align="center" width="150">
          <template #default="{ row }">
            <el-input v-if="row.isEditing" v-model="row.function" size="small" />
            <span v-else>{{ row.function }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="{ row, $index }">
            <template v-if="row.isEditing">
              <el-button type="primary" size="small" @click="saveImmunization(row)">
                <el-icon><Check /></el-icon>
                保存
              </el-button>
              <el-button size="small" @click="cancelEdit(row)">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </template>
            <template v-else>
              <el-button link type="success" size="small" @click="editImmunization(row)">
                <el-icon><Edit /></el-icon>
                修改
              </el-button>
              <el-button link type="danger" size="small" @click="deleteImmunization($index)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 动检证 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>动检证</h3>
          <span class="upload-tip">支持多张图片上传</span>
        </div>
      </template>

      <div class="certificate-uploads">
        <div class="uploaded-certificates">
          <div
            v-for="(cert, idx) in quarantineCertificates"
            :key="cert.id"
            class="certificate-item"
          >
            <img v-if="cert.imagePath" :src="cert.imagePath" class="certificate-img" />
            <el-icon class="img-delete-x" @click="deleteCertificate(cert.id)">
              <Close />
            </el-icon>
          </div>
          <!-- 上传按钮，最多9张 -->
          <label v-if="quarantineCertificates.length < 10" class="certificate-upload">
            <input
              type="file"
              accept="image/*"
              name="ImageFile"
              style="display: none"
              @change="handleCertificateUpload"
            />
            <el-icon class="plus-icon"><Plus /></el-icon>
          </label>
        </div>
      </div>
    </el-card>

    <!-- 企业信息 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>企业信息</h3>
          <el-button type="primary" size="small" @click="openEnterpriseSettings">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
        </div>
      </template>

      <div class="enterprise-details" :data="EnterpriseData">
        <div class="info-grid">
          <div class="info-item">
            <label>养殖场</label>
            <span>{{ EnterpriseData.farm || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>负责人</label>
            <span>{{ EnterpriseData.leader || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>存栏数量</label>
            <span>{{ EnterpriseData.saves || 0 }}只</span>
          </div>
          <div class="info-item">
            <label>生产批次</label>
            <span>{{ EnterpriseData.batch || '未设置' }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 企业照片 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>企业照片</h3>
          <span class="upload-tip">支持多张图片上传</span>
        </div>
      </template>

      <div class="photo-uploads">
        <div class="uploaded-photos">
          <div
            v-for="(photo, idx) in enterprisePhotos"
            :key="photo.id"
            class="photo-item"
          >
            <img v-if="photo.imagePath" :src="photo.imagePath" class="photo-img" />
            <el-icon class="img-delete-x" @click="deletePhoto(photo.id)">
              <Close />
            </el-icon>
          </div>
          <!-- 上传按钮，最多9张 -->
          <label v-if="enterprisePhotos.length < 10" class="photo-upload">
            <input
              type="file"
              accept="image/*"
              name="ImageFile"
              style="display: none"
              @change="handlePhotoUpload"
            />
            <el-icon class="plus-icon"><Plus /></el-icon>
          </label>
        </div>
      </div>
    </el-card>

    <!-- 养殖信息设置弹框 -->
    <el-dialog v-model="breedingDialogVisible" title="养殖信息设置" width="600px">
      <el-form :model="breedingForm" :rules="breedingRules" ref="breedingFormRef" label-width="120px">
        <el-form-item label="品种:" prop="variety">
          <el-input v-model="breedingForm.variety" placeholder="请输入品种" />
        </el-form-item>
        <el-form-item label="来源:" prop="source">
          <el-select v-model="breedingForm.source" placeholder="请选择来源">
            <el-option label="采购" value="采购" />
            <el-option label="自繁" value="自繁" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="饲养天数:" prop="rearingDays">
          <el-input-number v-model="breedingForm.rearingDays" :min="1" :max="999" placeholder="饲养天数" />
        </el-form-item>
        <el-form-item label="饲料品牌:" prop="brand">
          <el-input v-model="breedingForm.brand" placeholder="请输入饲料品牌" />
        </el-form-item>
        <el-form-item label="饲养负责人:" prop="rearingLeader">
          <el-input v-model="breedingForm.rearingLeader" placeholder="请输入饲养负责人" />
        </el-form-item>
        <el-form-item label="出栏日期:" prop="outDate">
          <el-date-picker v-model="breedingForm.outDate" type="date" placeholder="选择出栏日期"   value-format="YYYY-MM-DD"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="breedingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBreedingInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 企业信息设置弹框 -->
    <el-dialog v-model="enterpriseDialogVisible" title="企业信息设置" width="600px">
      <el-form :model="enterpriseForm" :rules="enterpriseRules" ref="enterpriseFormRef" label-width="120px">
        <el-form-item label="养殖场:" prop="farm">
          <el-input v-model="enterpriseForm.farm" placeholder="请输入养殖场名称" />
        </el-form-item>
        <el-form-item label="负责人:" prop="leader">
          <el-input v-model="enterpriseForm.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="存栏数量:" prop="saves">
          <el-input-number v-model="enterpriseForm.saves" :min="1" placeholder="存栏数量" />
        </el-form-item>
        <el-form-item label="生产批次:">
          <el-input v-model="enterpriseForm.batch" disabled placeholder="生产批次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="enterpriseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEnterpriseInfo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Close, Setting, Check, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { id } from 'element-plus/es/locales.mjs'
import { Traceability } from '@/Utils/Http'
import { useRoute, } from 'vue-router'
const route=useRoute()


// 免疫信息接口定义
interface ImmunizationItem {
  id?: number;
  rearingDays: number;
  way: string;
  function: string;
  batch: string;
  isDel: boolean;
  isEditing?: boolean;
}

interface CertificateItem {
  id: string
  imagePath?: string
  url?: string
}

interface PhotoItem {
  id: string
  imagePath?: string
  url?: string
}

// 免疫信息数据
const immunizationList = ref<ImmunizationItem[]>([]) 

// 动检证数据
const quarantineCertificates = ref<CertificateItem[]>([])

// 企业照片数据
const enterprisePhotos = ref<PhotoItem[]>([])

// 弹框相关
const breedingDialogVisible = ref(false)
const enterpriseDialogVisible = ref(false)

// 养殖信息表单
const breedingForm = reactive({
  id:0,
  variety: '',
  source: '',
  rearingDays: 0,
  brand: '',
  rearingLeader: '',
  outDate: '',
  batch:route.query.batch
})

// 企业信息数据
const EnterpriseData = ref<any>([])

// 企业信息表单
const enterpriseForm = reactive({
  id: 0,
  farm: '',
  leader: '',
  saves: 0,
  batch: route.query.batch
})

// 表单引用
const breedingFormRef = ref()
const enterpriseFormRef = ref()

// 养殖信息验证规则
const breedingRules = {
  variety: [
    { required: true, message: '请输入品种', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请选择来源', trigger: 'change' }
  ],
  rearingDays: [
    { required: true, message: '请输入饲养天数', trigger: 'blur' }
  ],
  brand: [
    { required: true, message: '请输入饲料品牌', trigger: 'blur' }
  ],
  rearingLeader: [
    { required: true, message: '请输入饲养负责人', trigger: 'blur' }
  ],
  outDate: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ]
}

// 企业信息验证规则
const enterpriseRules = {
  farm: [
    { required: true, message: '请输入养殖场名称', trigger: 'blur' }
  ],
  leader: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ],
  saves: [
    { required: true, message: '请输入存栏数量', trigger: 'blur' }
  ]
}

// 获取免疫信息列表
const getImmunityList = () => {
  Traceability.get('/Cultivation/GetImmunityQuery?Bath='+route.query.batch).then(res => {
    if (res.data.code == 200) {
      immunizationList.value = res.data.data
    }
  }).catch(error => {
    console.error('获取免疫信息失败:', error)
  })
}

// 新增免疫信息行
const addImmunizationRow = () => {
  const newItem: ImmunizationItem = {
    rearingDays: 0,
    way: '',
    function: '',
    batch: route.query.batch as string || '',
    isDel: false,
    isEditing: true
  }
  immunizationList.value.push(newItem)
}

// 编辑免疫信息
const editImmunization = (row: ImmunizationItem) => {
  row.isEditing = true
}

// 保存免疫信息
const saveImmunization = async (row: ImmunizationItem) => {
  // 验证必填字段
  if (!row.rearingDays || !row.way || !row.function) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    if (row.id) {
      // 修改现有记录
      const updateData = {
        id: row.id,
        rearingDays: Number(row.rearingDays),
        way: row.way,
        function: row.function,
        batch: row.batch
      }
      const res = await Traceability.post('/Cultivation/UpdImmunity', updateData)
      if (res.data.code == 400) {
        ElMessage.success('修改成功')
        row.isEditing = false
        // 修改成功后直接更新本地数据，不重新获取
        row.rearingDays = Number(row.rearingDays)
      } else {
        ElMessage.error(res.data.msg || '修改失败')
      }
    } else {
      // 新增记录
      const addData = {
        rearingDays: Number(row.rearingDays),
        way: row.way,
        function: row.function,
        batch: row.batch,
        isDel: false
      }
      const res = await Traceability.post('/Cultivation/AddImmunity', {
        immunityModels: [addData]
      })
      if (res.data.code == 300) {
        ElMessage.success('添加免疫保健信息成功')
        // 添加成功后直接更新本地数据，设置ID并退出编辑状态
        row.id = res.data.data?.id || Date.now() // 使用返回的ID或生成临时ID
        row.isEditing = false
        row.rearingDays = Number(row.rearingDays)
        console.log('添加成功，当前数据:', immunizationList.value)
      } else {
        ElMessage.error(res.data.msg || '添加失败')
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消编辑
const cancelEdit = (row: ImmunizationItem) => {
  if (row.id) {
    // 如果是现有记录，退出编辑状态，保持原数据
    row.isEditing = false
  } else {
    // 如果是新记录，直接删除
    const index = immunizationList.value.findIndex(item => item === row)
    if (index > -1) {
      immunizationList.value.splice(index, 1)
    }
  }
}

// 删除免疫信息
const deleteImmunization = async (index: number) => {
  const row = immunizationList.value[index]
  
  try {
    await ElMessageBox.confirm('确认删除免疫信息么?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (!row.id) {
      // 如果是新记录，直接删除
      immunizationList.value.splice(index, 1)
      return
    }

    // 调用删除接口（这里假设有删除接口）
    const res = await Traceability.delete('/Cultivation/DelImmunity?id=' + row.id)
    if (res.data.code == 500) {
      ElMessage.success('删除免疫信息成功')
      immunizationList.value.splice(index, 1)
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}



// 创建文件输入元素用于多图片上传
const createFileInput = (accept: string = 'image/*', multiple: boolean = true) => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = accept
  input.multiple = multiple
  input.style.display = 'none'
  return input
}

// 处理文件选择
const handleFileSelect = (files: FileList, targetArray: any[]) => {
  const maxFiles = 10 // 最大上传数量
  if (files.length + targetArray.length > maxFiles) {
    ElMessage.warning(`最多只能上传${maxFiles}张图片`)
    return
  }

  Array.from(files).forEach(file => {
    if (file.type.startsWith('image/')) {
      const reader = new FileReader()
      reader.onload = (e) => {
        if (e.target?.result) {
          targetArray.push({ url: e.target.result as string })
        }
      }
      reader.readAsDataURL(file)
    } else {
      ElMessage.warning('请选择图片文件')
    }
  })
}

// 获取动检证图片
const fetchCertificateImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 2, BatchNo: batch }
    })
    
    // 过滤出有效的图片数据
    quarantineCertificates.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取动检证图片失败:', error)
  }
}

// 上传动检证图片
const handleCertificateUpload = async (event: Event) => {
  const files = (event.target as HTMLInputElement).files
  if (!files || !files.length) return
  
  if (quarantineCertificates.value.length + files.length > 9) {
    ElMessage.warning('最多只能上传9张图片')
    return
  }
  
  const formData = new FormData()
  formData.append('ImageFile', files[0])
  formData.append('BatchNo', route.query.batch as string)
  formData.append('ImageType', '2')
  
  try {
    const res = await Traceability.post('/UploadBatchImage/UploadBatch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.data && res.data.code === 300) {
      ElMessage.success('动检证上传成功')
      // 上传成功后刷新图片列表
      await fetchCertificateImages()
    } else {
      ElMessage.error(res.data?.message || '上传失败')
    }
  } catch (error) {
    console.error('上传动检证图片失败:', error)
    ElMessage.error('上传失败')
  }
  
  // 清空文件输入，允许重复选择相同文件
  ;(event.target as HTMLInputElement).value = ''
}

// 删除动检证图片
const deleteCertificate = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定删除动检证图片么?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await Traceability.delete('/UploadBatchImage/DelBatchImage', {
      params: {
        Id: id,
        ImageType: '2'
      }
    })
    
    // 检查响应状态
    if (res.data && res.data.code === 500) {
      ElMessage.success('动检证删除成功')
      // 删除成功后刷新图片列表
      await fetchCertificateImages()
    } else {
      ElMessage.error(res.data?.message || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    console.error('删除动检证图片失败:', error)
    ElMessage.error('删除失败')
  }
}

// 获取企业照片
const fetchPhotoImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 3, BatchNo: batch }
    })
    
    // 过滤出有效的图片数据
    enterprisePhotos.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取企业照片失败:', error)
  }
}

// 上传企业照片
const handlePhotoUpload = async (event: Event) => {
  const files = (event.target as HTMLInputElement).files
  if (!files || !files.length) return
  
  if (enterprisePhotos.value.length + files.length > 9) {
    ElMessage.warning('最多只能上传9张图片')
    return
  }
  
  const formData = new FormData()
  formData.append('ImageFile', files[0])
  formData.append('BatchNo', route.query.batch as string)
  formData.append('ImageType', '3')
  
  try {
    const res = await Traceability.post('/UploadBatchImage/UploadBatch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.data && res.data.code === 300) {
      ElMessage.success('企业照片上传成功')
      // 上传成功后刷新图片列表
      await fetchPhotoImages()
    } else {
      ElMessage.error(res.data?.message || '上传失败')
    }
  } catch (error) {
    console.error('上传企业照片失败:', error)
    ElMessage.error('上传失败')
  }
  
  // 清空文件输入，允许重复选择相同文件
  ;(event.target as HTMLInputElement).value = ''
}

// 删除企业照片
const deletePhoto = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定删除企业照片么?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await Traceability.delete('/UploadBatchImage/DelBatchImage', {
      params: {
        Id: id,
        ImageType: '3'
      }
    })
    
    // 检查响应状态
    if (res.data && res.data.code === 500) {
      ElMessage.success('删除成功')
      // 删除成功后刷新图片列表
      await fetchPhotoImages()
    } else {
      ElMessage.error(res.data?.message || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    console.error('删除企业照片失败:', error)
    ElMessage.error('删除失败')
  }
}

// 图片预览
const previewImage = (url: string) => {
  // 这里可以实现图片预览功能，比如使用Element Plus的ImageViewer
  ElMessage.info('图片预览功能')
}

// 格式化日期为年月日格式
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 打开养殖信息设置弹框
const openBreedingSettings = () => {
  // 反填现有数据
  if (CultivationData.value && Object.keys(CultivationData.value).length > 0) {
    breedingForm.id = CultivationData.value.id || 0
    breedingForm.variety = CultivationData.value.variety || ''
    breedingForm.source = CultivationData.value.source || ''
    breedingForm.rearingDays = CultivationData.value.rearingDays || 0
    breedingForm.brand = CultivationData.value.brand || ''
    breedingForm.rearingLeader = CultivationData.value.rearingLeader || ''
    breedingForm.outDate = CultivationData.value.outDate || ''
  }
  breedingDialogVisible.value = true
}

// 打开企业信息设置弹框
const openEnterpriseSettings = () => {
  // 反填现有数据
  if (EnterpriseData.value && Object.keys(EnterpriseData.value).length > 0) {
    enterpriseForm.id = EnterpriseData.value.id || 0
    enterpriseForm.farm = EnterpriseData.value.farm || ''
    enterpriseForm.leader = EnterpriseData.value.leader || ''
    enterpriseForm.saves = EnterpriseData.value.saves || 0
    enterpriseForm.batch = EnterpriseData.value.batch || route.query.batch
  }
  enterpriseDialogVisible.value = true
}

// 保存养殖信息
const saveBreedingInfo = async () => {
  // 表单验证
  if (!breedingFormRef.value) return
  
  try {
    await breedingFormRef.value.validate()
    
    console.log('保存养殖信息:', breedingForm)
    
    // 统一为重新添加，后端会先逻辑删除同批次数据，再重新添加
    Traceability.post('/Cultivation/AddCultivation', breedingForm).then(res => {
      if (res.data.code == 300) {
        ElMessage.success('养殖信息保存成功')
        getCultivation()
        breedingDialogVisible.value = false
      } else {
        ElMessage.error(res.data.msg || '养殖信息保存失败')
      }
    }).catch(error => {
      console.error('保存养殖信息失败:', error)
      ElMessage.error('养殖信息保存失败')
    })
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}
// 获取养殖信息
const CultivationData = ref<any>([])
const getCultivation = () => {
  Traceability.get('/Cultivation/GetCultivationQuery', {
    params: {
    Batch:route.query.batch
  }}).then(res => {
    CultivationData.value=res.data.data
  })
}

// 获取企业信息
const getEnterpriseInfo = () => {
  // 预留接口调用
  Traceability.get('/Cultivation/GetCultivationCommpany', {
    params: { Batch: route.query.batch }
  }).then(res => {
    if (res.data.code == 200) {
      EnterpriseData.value = res.data.data
    }
  }).catch(error => {
    console.error('获取企业信息失败:', error)
  })
  
  // 暂时使用死值，生产批次从路由获取
  // EnterpriseData.value = {
  //   farm: '',
  //   leader: '',
  //   saves: 0,
  //   batch: route.query.batch || 'BATCH001'
  // }
  
  // 同时更新表单中的生产批次
  enterpriseForm.batch = route.query.batch || 'BATCH001'
}

onMounted(() => {
  getCultivation()
  getImmunityList()
  getEnterpriseInfo()
  fetchCertificateImages()
  fetchPhotoImages()
})

// 保存企业信息
const saveEnterpriseInfo = async () => {
  // 表单验证
  if (!enterpriseFormRef.value) return
  
  try {
    await enterpriseFormRef.value.validate()
    
    console.log('保存企业信息:', enterpriseForm)
    
    // 统一为重新添加，后端会先逻辑删除同批次数据，再重新添加
    Traceability.post('/Cultivation/AddCultivationCommpany', enterpriseForm).then(res => {
      if (res.data.code == 300) {
        ElMessage.success('企业信息保存成功')
        getEnterpriseInfo()
        enterpriseDialogVisible.value = false
      } else {
        ElMessage.error(res.data.msg || '企业信息保存失败')
      }
    }).catch(error => {
      console.error('保存企业信息失败:', error)
      ElMessage.error('企业信息保存失败')
    })
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}
</script>

<style scoped>
.breeding-info {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  margin-bottom: 16px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 6px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #7f8c8d;
  font-size: 13px;
}

/* 卡片样式 */
.info-card {
  margin-bottom: 16px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.info-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.upload-tip {
  color: #909399;
  font-size: 11px;
  background: #f0f9ff;
  padding: 3px 6px;
  border-radius: 3px;
  border: 1px solid #b3d8ff;
}

/* 信息网格布局 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  padding: 12px 0;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  color: #606266;
  font-size: 12px;
  font-weight: 500;
}

.info-item span {
  color: #2c3e50;
  font-size: 14px;
  font-weight: 400;
  padding: 6px 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

/* 表格样式 */
.immunization-table {
  border-radius: 8px;
  overflow: hidden;
}

.immunization-table :deep(.el-table__header) {
  background: #f8f9fa;
}

.immunization-table :deep(.el-table__header th) {
  background: #f8f9fa;
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 2px solid #e9ecef;
}

.immunization-table :deep(.el-table__row:hover) {
  background: #f0f9ff;
}

/* 图片上传区域 */
.certificate-uploads,
.photo-uploads {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: flex-start;
}

.uploaded-certificates,
.uploaded-photos {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.certificate-item,
.photo-item {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.certificate-item:hover,
.photo-item:hover {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.certificate-item img,
.photo-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.certificate-item:hover img,
.photo-item:hover img {
  transform: scale(1.05);
}

.certificate-overlay,
.photo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.certificate-item:hover .certificate-overlay,
.photo-item:hover .photo-overlay {
  opacity: 1;
}

.remove-icon {
  color: white;
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.remove-icon:hover {
  background: #ff4757;
  transform: scale(1.1);
}

/* 新的动检证上传样式 */
.certificate-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.img-delete-x {
  position: absolute;
  top: 4px;
  right: 4px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  background: rgba(255, 0, 0, 0.7);
  transition: all 0.3s ease;
  z-index: 10;
}

.img-delete-x:hover {
  background: rgba(255, 0, 0, 0.9);
  transform: scale(1.1);
}

.certificate-upload {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.certificate-upload:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.plus-icon {
  font-size: 24px;
  color: #999;
  transition: color 0.3s ease;
}

.certificate-upload:hover .plus-icon {
  color: #409eff;
}

/* 企业照片上传样式 */
.photo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.photo-upload {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.photo-upload:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.photo-upload .plus-icon {
  font-size: 24px;
  color: #999;
  transition: color 0.3s ease;
}

.photo-upload:hover .plus-icon {
  color: #409eff;
}

.upload-btn {
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s ease;
  background: #fafafa;
}

.upload-btn:hover {
  border-color: #409eff;
  color: #409eff;
  background: #f0f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.upload-btn .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.upload-btn span {
  font-size: 10px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .breeding-info {
    padding: 12px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .certificate-item,
  .photo-item,
  .upload-btn {
    width: 80px;
    height: 80px;
  }
  
  .upload-btn .el-icon {
    font-size: 20px;
  }
  
  .upload-btn span {
    font-size: 9px;
  }
}

/* 按钮样式优化 */
.el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #5a9eff 100%);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #5a9eff 0%, #409eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 表格按钮样式 */
.immunization-table :deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 6px;
}

.immunization-table :deep(.el-button--small .el-icon) {
  margin-right: 4px;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
}

:deep(.el-dialog__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 12px 20px 20px;
  border-top: 1px solid #e9ecef;
}

</style>

